<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/5/23
 * Time: 上午9:52
 */

namespace common\jobs;

use common\models\NoticeApiLog;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use yii\base\BaseObject;
use yii\base\InvalidArgumentException;
use yii\queue\Queue;
use yii\queue\RetryableJobInterface;

/**
 * 绑定手机号和优惠券
 * Class PromotionUserJob
 * @package common\jobs
 */
class NoticeApiJob extends BaseObject implements RetryableJobInterface
{

    public $phone;

    public $couponId;

    /**
     * @param Queue $queue which pushed and is handling the job
     */
    public function execute($queue)
    {
        $data = ['phone' => $this->phone, 'coupon_id' => $this->couponId];
        $model = NoticeApiLog::find()->where(['phone' => $this->phone, 'coupon_id' => $this->couponId])->one();
        if ($model == null) {
            $model = new NoticeApiLog();
            $model->phone = $this->phone;
            $model->coupon_id = $this->couponId;
            $model->attempt = 1;
        } else {
            $model->attempt = $model->attempt + 1;
        }
        try {
            $res = $this->sendRequest($data);
            if ($res->code == 1) {
                $model->status = NoticeApiLog::STATUS_SUCCESS;
                $model->msg = $res->msg;
                $model->save();
                return true;
            } else {
                $model->status = NoticeApiLog::STATUS_FAILURE;
                $model->msg = $res->Result;
                $model->save();
                throw new InvalidArgumentException($res->msg . '-phone=' . $this->phone . '-coupon_id=' . intval($this->couponId));
            }
        } catch (\GuzzleHttp\Exception\ServerException $e) {
            $model->status = NoticeApiLog::STATUS_FAILURE;
            $model->msg = $e->getMessage();
            $model->save();
            throw  new \Exception($e->getMessage());
        } catch (RequestException $e) {
            $model->status = NoticeApiLog::STATUS_FAILURE;
            $model->msg = $e->getMessage();
            $model->save();
            throw  new \Exception($e->getMessage());
        } catch (\Exception $e) {
            $model->status = NoticeApiLog::STATUS_FAILURE;
            $model->msg = $e->getMessage();
            $model->save();
            throw  $e;
        }
    }

    public function sendRequest($data)
    {
        $apiUrl = getenv("ISSURE_COUPON_API") . 'api/user_coupon';
        $client = new Client();
        try {
            $responses = $client->request(
                "POST",
                $apiUrl,
                [
                    'headers' => [
                        'Content-Type' => 'application/json;charset=utf-8',
                    ],
                    'body' => json_encode($data),
                ]
            );
            return $responseData = json_decode($responses->getBody()->getContents());
        } catch (\GuzzleHttp\Exception\ServerException $e) {
            throw  $e;
        } catch (RequestException $e) {
            throw  $e;
        } catch (\Exception $e) {
            throw  $e;
        }
    }

    /**
     * @return int time to reserve in seconds
     */
    public function getTtr()
    {
        return 0;
    }

    /**
     * @param int $attempt number
     * @param \Exception $error from last execute of the job
     * @return bool
     */
    public function canRetry($attempt, $error)
    {
        return $attempt < 5;
    }
}
